package service.impl;

import Dao.OrderDao;
import Dao.OrderItemDao;
import Dao.impl.OrderServiceI;
import pojo.*;
import service.BookService;
import service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderSrtviceLmpl implements OrderService {
   private OrderDao orderDao = new OrderServiceI();
   private OrderItemDao orderItem = new OrderServiceI();
   BookService books = new BookServiceImpl();

    @Override
    public String createOrder(Cart cart, Integer id) {
        //订单号 随机获得
        String orderId = "CJH"+System.currentTimeMillis()+""+id;
        //创建一个订单对象
        Order order = new Order(orderId,new Date(),cart.getTotalPrice(),0,id);
        //保存订单
        orderDao.saveOrder(order);
//        int i = 12/0;
        Map<Integer, CartItem> items = cart.getItems();
        for(Map.Entry<Integer,CartItem> entry : items.entrySet()){
            CartItem value = entry.getValue();
            OrderItem orderItem1 = new OrderItem(null,value.getName(),value.getCount(), value.getPrice(),value.getTotalPrice(),orderId);
            //下单之后要增加销量和减少库存
            Book book = books.queryBookById(value.getId());
            //防止出现负数
            if(book.getStock()>=value.getCount()){
                book.setSales(book.getSales()+value.getCount());
                book.setStock(book.getStock()-value.getCount());
                books.updateBook(book);
            }else{
                book.setStock(book.getStock()+100);
                book.setSales(book.getSales()+value.getCount());
                book.setStock(book.getStock()-value.getCount());
                books.updateBook(book);
            }
            orderItem.saveOrderItem(orderItem1);
        }
        cart.clearCart();
        return orderId;
    }

    @Override
    public List<Order> showAllOrders() {
       return orderDao.queryOrders();
    }

    @Override
    public void sendOrder(String id) {
        orderDao.changeOrderStatus(id,1);
    }

    @Override
    public Order showOrderDetail(String id) {
//        String sql = "SELECT * FROM order_item o" +
//                "LEFT JOIN  Order_book j ON o.order_id = j.order_id" +
//                "LEFT JOIN  books b ON j.user_id = b.id WHERE user_id = ?;";
//        return orderItem.queryOrderItemsByOrderId(id);
        return null;
    }

    @Override
    public List<Order> showMyOrders(Integer id) {
        return orderDao.queryOrdersByUserId(id);
    }

    @Override
    public void receiveOrder(Integer id) {

    }
}
